package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

@Api(tags = "service-payment模块阿里支付控制器")
@Controller
@RequestMapping("api/payment/alipay")
public class AlipayController {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;

    @ApiOperation("生成支付二维码")
    @GetMapping("submit/{orderId}")
    @ResponseBody
    public String submitOrder(@PathVariable Long orderId){
        String form = "";
        try {
            form = alipayService.createaliPay(orderId);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }


    @ApiOperation("支付成功后同步回调")
    @GetMapping("callback/return")
    public String callBack(){
        return "redirect:"+ AlipayConfig.return_order_url;
    }

    @ApiOperation("支付成功后异步回调")
    @PostMapping("callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String,String> paramMap){
        System.out.println("调用异步回调了");
        boolean flag = false;
        try {
            flag = AlipaySignature.rsaCheckV1(paramMap,AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        String tradeStatus = paramMap.get("trade_status");
        String outTradeNo = paramMap.get("out_trade_no");
        if (flag){
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                PaymentInfo paymentInfo = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
                if (paymentInfo == null){
                    return "failure";
                }
                if (PaymentStatus.PAID.name().equals(paymentInfo.getPaymentStatus())
                        || PaymentStatus.CLOSED.name().equals(paymentInfo.getPaymentStatus())){
                    return "failure";
                }
                String totalAmount = paramMap.get("total_amount");
                //if (new BigDecimal(totalAmount).compareTo(paymentInfo.getTotalAmount()) != 0){
                if (new BigDecimal(totalAmount).compareTo(new BigDecimal("0.01")) != 0){
                    return "failure";
                }
                paymentService.paySuccess(outTradeNo,PaymentType.ALIPAY.name(),paramMap);
                return "success";
            }else {
                return "failure";
            }
        }else {//验签失败
            return "failure";
        }
    }


    // 发起退款！http://localhost:8205/api/payment/alipay/refund/20
    @RequestMapping("refund/{orderId}")
    @ResponseBody
    public Result refund(@PathVariable Long orderId){
        // 调用退款接口
        boolean flag = alipayService.refund(orderId);

        return Result.ok(flag);

    }

    //根据订单id取消支付宝的交易
    @ApiOperation("取消支付宝的交易")
    @GetMapping("closePay/{orderId}")
    @ResponseBody
    public Boolean closePay(@PathVariable Long orderId){
        Boolean aBoolean = alipayService.closePay(orderId);
        return aBoolean;
    }

    //根据订单id 查询支付宝交易
    @ApiOperation("根据订单id 查询支付宝交易")
    @GetMapping("checkPay/{orderId}")
    @ResponseBody
    public Boolean checkPay(@PathVariable Long orderId){
        Boolean aBoolean = alipayService.checkPay(orderId);
        return aBoolean;
    }

    //根据out_trade_no以及 支付方式 查询支付信息
    @ApiOperation("根据out_trade_no以及 支付方式 查询支付信息")
    @GetMapping("getPaymentInfo/{outTradeNo}")
    @ResponseBody
    public PaymentInfo getPaymentInfo(@PathVariable String outTradeNo){
        //目前只是查询支付宝支付方式的支付信息
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
        if (null!=paymentInfo){
            return paymentInfo;
        }
        return null;
    }




}
